from myback.models import *
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import datetime
import time
from Django_Admin.settings import *
import json
from utils.process_opera import ProcessOperator
from django.core import serializers


# 新建策略接口
def stgadd(request):
    """
    本接口执行新建策略
    """
    try:
        stgname = request.POST.get("stgname")
        #### 取出最大的策略id 并自增
        TStrategy.objects.using("BackTestDB").values("StgID").order_by("-StgID")
        a_list = TStrategy.objects.using("BackTestDB").values("StgID").order_by("-StgID")
        a_list = list(a_list)
        stgid = a_list[0].get("StgID")
        stgid += 1
        #### 取出customerid
        customerid = request.session.get("customerid")
        creatime = datetime.datetime.now()
        #### t_strategy表落库
        TStrategy.objects.using("BackTestDB").create(
            CustomerID=customerid,
            StgID=stgid,
            StgName=stgname,
            CreateTime=creatime,
            Status="1",
            BackTest=0
        )
        return JsonResponse({"msg": stgid, "type": 1}, safe=False)
    except Exception as e:
        return JsonResponse({"msg": e, "type": 0}, safe=False)


# 策略查询接口
def stg_search(request):
    """
    本接口执行策略查询
    """
    try:
        stg_obj_list = serializers.serialize("json", TStrategy.objects.using("BackTestDB").all())
        return JsonResponse({"stg_obj_list": stg_obj_list, "type": 1}, safe=False)
    except Exception as e:
        return JsonResponse({"stg_obj_list": str(e), "type": 0}, safe=False)


# 策略删除接口
def stg_del(request):
    """
    本接口执行策略删除
    """
    stgid = request.POST.get("stgid")
    try:
        if TStrategy.objects.using("BackTestDB").filter(StgID=stgid).exists():
            TStrategy.objects.using("BackTestDB").filter(StgID=stgid).delete()
            if TBackapproval.objects.using("BackTestDB").filter(stgid=stgid).exists():
                TBackapproval.objects.using("BackTestDB").filter(stgid=stgid).delete()
            return HttpResponse("y")
    except Exception as e:
        return HttpResponse(str(e))


# 前台点击回测后执行该接口
def opt_stg(request):
    """
    本接口执行回测整个流程，
    包括
        新建落库
        打包
        启动
    后两步调用其他接口
    """
    stgid = request.POST.get("stgid")
    stgcode = request.POST.get("stgcode")
    date = request.POST.get("rundate")
    date = json.loads(date)
    ##### 配置文件
    stgconfig = f"""[strategy_mode]\nRun_Mode = 1\nServer_Host = 172.19.228.219\nServer_Port = 50000\n\n[strategy_back]\nLog_Level = 2\nStart_Time = {date.get("startdate")} 00:00:00\nEnd_Time = {date.get("endate")} 23:59:59 
                """

    # """
    # 将该配置文件写入util文件夹下
    # 该文件夹下存在启动进程语句
    # 否则会报错，找不到strategy_modo
    # """
    # f = open(BASE_DIR + '/utils/strategy.ini', 'w', encoding="utf8")
    # f.write(stgconfig)

    ##### backapproval表落库
    if TBackapproval.objects.using("BackTestDB").filter(stgid=stgid).exists():
        TBackapproval.objects.using("BackTestDB").filter(stgid=stgid).update(
            stgfile=stgcode,
            confile=stgconfig,
            packstatus="0",
            envid="1",
            status="",
            packtime="1970-01-01",
            packmsg="",
            runpath=""
        )
    else:
        TBackapproval.objects.using("BackTestDB").create(
            stgid=stgid,
            stgfile=stgcode,
            confile=stgconfig,
            packstatus="0",
            envid="1",
            status="",
            packtime="1970-01-01",
            packmsg="",
            runpath=""
        )

    ##### 新增完数据库之后停顿2秒，等待打包程序打包结束
    time.sleep(2)
    ##### 轮询数据库，策略打包成功的话执行启动
    while True:
        time.sleep(1)
        status = TBackapproval.objects.using("BackTestDB").values("status").filter(stgid=stgid).first().get("status")
        # 执行启动进程脚本
        if status == "0":
            print("打包成功，执行一次轮询")
            propera_obj = ProcessOperator()
            propera_obj.start_process(stgid)
            # return JsonResponse({"msg": "y", "type": 2}, safe=False)
        elif status == "1":
            # 如果已经运行成功，则去run表中拿到batchid，然后传给前台
            # 用于轮询return或summary表
            batchid = TBackrun.objects.using("BackTestDB").values("batchid").filter(stgid=stgid).order_by(
                "-batchid").first().get("batchid")
            if TBackreturn.objects.using("BackTestDB").filter(batchid=batchid, stgid=stgid).exists():
                print("轮询执行结束")
                return JsonResponse({"msg": batchid}, safe=False)
            else:
                print("策略运行成功，执行一次轮询")
                continue
        else:
            print("")
            continue
